﻿using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Request.Customer;
using CarEdge.Infrastructure.Dto.Request.VIP;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.IOC;
using CarEdge.Infrastructure.IOC.Customer;
using CarEdge.Infrastructure.IOC.Dic;
using CarEdge.Infrastructure.IOC.Order;
using CarEdge.Infrastructure.IOC.Product;
using CarEdge.Infrastructure.IOC.VIP;
using CarEdge.Service.Interface.Count;
using Microsoft.EntityFrameworkCore;

namespace CarEdge.Service.Instance.Count
{
    [Inject_]
    public class Count_Service : Base_Service, I_Count_Service

    {
        private readonly Customer_IOC _customer_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly VIP_IOC _vIP_IOC;
        private readonly Dic_IOC _dic_IOC;
        private readonly Product_IOC _product_IOC;
        private readonly Order_IOC _order_IOC;

        public Count_Service(Customer_IOC customer_IOC, Login_IOC login_IOC, VIP_IOC vIP_IOC, Dic_IOC dic_IOC, Product_IOC product_IOC, Order_IOC order_IOC)
        {
            _customer_IOC = customer_IOC;
            _login_IOC = login_IOC;
            _vIP_IOC = vIP_IOC;
            _dic_IOC = dic_IOC;
            _product_IOC = product_IOC;
            _order_IOC = order_IOC;
        }

        /// <summary>
        /// 获取成功率最高的三个客户
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> GetcustomerCount()
        {
            var iq = await _customer_IOC._customer_EFCore.QueryAll(d => d.CSuccessPercent < 100).Take(3).OrderByDescending(d => d.CSuccessPercent).ToListAsync();
            var data = new List<Customer_Request_Dto>();

            iq.ForEach(d =>
            {
                data.Add(new Customer_Request_Dto
                {
                    name = d.CName,
                    success = d.CSuccessPercent,
                    responsibility = d.CResponsibility,
                    nexttime = d.CNextTime!.Value.ToString("yyyy-MM-dd:HH:mm"),
                });
            });
            data.ForEach(d =>
            {
                d.responsibility = _login_IOC._sys_User_EFCore.QueryAll(e => d.responsibility == e.Uid).Select(f => f.Uname).Single();
            });

            return Result(1, data: data);

        }

        /// <summary>
        /// 获取最近一周的会员增长数据
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetWeekVipCount()
        {
            // 获取当前日期的时间范围（近一周，以今天为结束日期）
            var endDate = DateTime.Now.Date; // 今天
            var tommorrow = endDate.AddDays(1);//明天
            var startDate = endDate.AddDays(-6);  // 一周前的日期
            // 查询本周内每天新增会员的数量
            var newVipDay = await _vIP_IOC._vIP_EFCore.QueryAll(d => d.VCreateTime >= startDate && d.VCreateTime <= tommorrow).GroupBy(d => d.VCreateTime!.Value.Date).Select(g => new { Date = g.Key, Count = g.Count() }).OrderBy(d => d.Date).ToListAsync();


            var result = Enumerable.Range(0, 7) // 生成 7 天的日期
                .Select(offset => startDate.AddDays(offset))
                .GroupJoin(
                    newVipDay,
                    date => date.Date,
                    m => m.Date.Date,
                    (date, group) => new
                    {
                        DayOfWeek = ConvertDateToChineseDayOfWeek(date),
                        Count = group.FirstOrDefault()?.Count ?? 0 // 如果某天没有数据，默认为 0
                    })
                .ToList();
            return Result(1, data: result);
        }
        /// <summary>
        /// 最近一周客户增长情况
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetWeekCustomerCount()
        {
            // 获取当前日期的时间范围（近一周，以今天为结束日期）
            var endDate = DateTime.Now.Date; // 今天
            var tommorrow = endDate.AddDays(1);//明天
            var startDate = endDate.AddDays(-6);  // 一周前的日期
            // 查询本周内每天新增会员的数量
            var newVipDay = await _customer_IOC._customer_EFCore.QueryAll(d=>d.CStatus==1 && d.CCreateTime >= startDate && d.CCreateTime <= tommorrow).GroupBy(d => d.CCreateTime!.Value.Date).Select(g => new { Date = g.Key, Count = g.Count() }).OrderBy(d => d.Date).ToListAsync();

            var result = Enumerable.Range(0, 7) // 生成 7 天的日期
                .Select(offset => startDate.AddDays(offset))
                .GroupJoin(
                    newVipDay,
                    date => date.Date,
                    m => m.Date,
                    (date, group) => new
                    {
                        DayOfWeek = ConvertDateToChineseDayOfWeek(date),
                        Count = group.FirstOrDefault()?.Count ?? 0 // 如果某天没有数据，默认为 0
                    })
                .ToList();
            return Result(1, data: result);
        }



        private object ConvertDateToChineseDayOfWeek(DateTime date)
        {
            string[] chineseDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
            return chineseDays[(int)date.DayOfWeek];
        }


        /// <summary>
        /// 获取各个会员等级的人数
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetTypeVipCount()
        {
            var dtype = await _dic_IOC._dictionary_Type_EFCore.QueryAll(d => d.DtKey == "vip_level").Select(d => d.DtId).SingleOrDefaultAsync();
            //所有的会员
            var did = await _dic_IOC._dictionary_EFCore.QueryAll(d => dtype!.Contains(d.DDtId!) && d.DValue != "1").OrderByDescending(d => d.DValue).ToListAsync();
            var data = new List<VIP_Request_Dto>();
            did.ForEach(d =>
            {
                data.Add(new VIP_Request_Dto
                {
                    count = _vIP_IOC._vIP_EFCore.QueryAll(f => f.VDid == d.DId).Count(),
                    name = d.DName,

                });
            });
            return Result(1, data: data);

        }
        /// <summary>
        /// 客户来源
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetSourceCount()
        {
            var iq = await _customer_IOC._customer_EFCore.QueryAll(d => d.CStatus == 1).GroupBy(d => d.CSource).Select(f => new
            {
                name = f.Key,
                value = f.Count(),

            }).ToListAsync();
            return Result(1, data: iq);
        }



        /// <summary>
        /// 套餐销量情况
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetPackCount()
        {
          

            //订单id
            var order =await  _order_IOC._order_Detail_EFCore.QueryAll(d=>d.OdIsPay==1).Select(d=>d.OdPId).ToListAsync();
            //筛选id
            var pid = await _product_IOC._productPackage_EFCore.QueryAll(d => order.Contains(d.PpId)).Select(d=>d.PpId).ToListAsync();

            var iq = await _order_IOC._order_Detail_EFCore.QueryAll(d => pid.Contains(d.OdPId!) && d.OdIsPay==1).GroupBy(d=>d.OdPName).Select(d=>new
            {
                name=d.Key,
                value=d.Sum(d=>d.OdCount),
            }).ToListAsync();




            return Result(1, data: iq);
        }


        /// <summary>
        /// 获取最近三个新加入的会员
        /// </summary>
        /// <returns></returns>

        public async Task<Api_Response_Dto> RecentVip()

        {

            var now = DateTime.Now;
            var iq = await _vIP_IOC._vIP_EFCore.QueryAll().OrderByDescending(d => d.VCreateTime).Take(3).ToListAsync();


            var result = iq.Select(d => new
            {
                name = _customer_IOC._customer_EFCore.QueryAll(c => c.CId == d.VCid).Select(c => c.CName).FirstOrDefault(),
                time = FormatTimeSpan(DateTime.Now - d.VCreateTime),
            }).ToList();

            return Result(1, data: result);

        }
        private string FormatTimeSpan(TimeSpan? timeSpan)
        {
            if (timeSpan == null)
            {
                return "0小时0分"; // 如果时间为空，返回默认值
            }
            TimeSpan nonNullableTimeSpan = timeSpan.Value;
            int days = nonNullableTimeSpan.Days;
            int hours = nonNullableTimeSpan.Hours;
            int minutes = nonNullableTimeSpan.Minutes;
            if (days == 0)
            {
                return $"{hours}小时{minutes}分";
            }
            if (nonNullableTimeSpan.Hours == 0)
            {
                return $"{minutes}分";
            }

            return $"{days}天{hours}小时{minutes}分";
        }

        /// <summary>
        /// 总销售额
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> TotalPrice()
        {
            var price = await _order_IOC._order_Pay_EFCore.QueryAll(d => d.PIsFinish == 1).Select(d => d.PMoney).SumAsync();

            return Result(1, data: price);
        }
        /// <summary>
        /// 今日销售额度
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> TodayPrice()
        {

            var now = DateTime.Now.Date;
            var next = now.AddDays(1);
            var price = await _order_IOC._order_Pay_EFCore.QueryAll(d => d.PIsFinish == 1 && d.PFinishTime >= now && d.PFinishTime <= next).Select(d => d.PMoney).ToListAsync();
            return Result(1, data: price.Sum());
        }
        /// <summary>
        /// 会员总人数
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> VipTotal()
        {
            var data = await _vIP_IOC._vIP_EFCore.QueryAll().ToListAsync();
            return Result(1, data: data.Count());
        }
        /// <summary>
        /// 客户总人数
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> CusTotal()
        {
            var data = await _customer_IOC._customer_EFCore.QueryAll(d => d.CStatus == 1).ToListAsync();
            return Result(1, data: data.Count());
        }
        /// <summary>
        /// 今日新增客户
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> TodayCusTotal()
        {
            var now = DateTime.Now.Date;
            var next = now.AddDays(1);
            var data = await _customer_IOC._customer_EFCore.QueryAll(d => d.CStatus == 1 && d.CCreateTime >= now && d.CCreateTime <= next).ToListAsync();
            return Result(1, data: data.Count());
        }
        /// <summary>
        /// 客户总体进度
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> AvgCusRecord()
        {
            var data = await _customer_IOC._customer_EFCore.QueryAll(d => d.CStatus == 1).Select(d => d.CSuccessPercent).ToListAsync();
            return Result(1, data: data.Average());
        }

        /// <summary>
        /// 今日新增会员
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> TodayVipCount()
        {
            var now = DateTime.Now.Date;//03-20  03-20 16:00
            var next = now.AddDays(1);
            var data = await _vIP_IOC._vIP_EFCore.QueryAll(d => d.VCreateTime >= now && d.VCreateTime < next).ToListAsync();
            return Result(1, data: data.Count());
        }
        /// <summary>
        /// 客户成功率
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetCusSuccessCount()
        {

            var iq = await _customer_IOC._customer_EFCore.QueryAll(d => d.CStatus == 1).Take(7).OrderBy(d => d.CSuccessPercent).Select(d => new
            {
                success = d.CSuccessPercent,
                name = d.CName,
            }).ToListAsync();
            return Result(1, data: iq);
        }
        /// <summary>
        /// 获取类型数量
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetTypeCount()
        {
            var ftype = await _product_IOC._sys_product_EFCore.QueryAll(d => d.Ptype == 1).CountAsync();
            var stype = await _product_IOC._sys_product_EFCore.QueryAll(d => d.Ptype == 2).CountAsync();

            return Result(1, data: new
            {
                ftype,
                stype,
            });

        }


        /// <summary>
        /// 服务类销量情况
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetFwSales()
        {

           

            //查询订单表里的产品id
            var iq=await _order_IOC._order_Detail_EFCore.QueryAll(d=>d.OdIsPay==1).Select(d=>d.OdPId).ToListAsync();
            //查询所有的服务类产品
            var allProduct = await _product_IOC._sys_product_EFCore.QueryAll(d=>d.Ptype==1).ToListAsync();
            //是否包含服务类的产品
            var od = await _product_IOC._sys_product_EFCore.QueryAll(d => iq.Contains(d.Pid)&& d.Ptype==1 ).Select(d=>d.Pid).ToListAsync();

            var salesData = await _order_IOC._order_Detail_EFCore.QueryAll(d => d.OdIsPay == 1 && od.Contains(d.OdPId!)).GroupBy(d => d.OdPId).Select(d=>new
            {
                pid = d.Key,
                Total = d.Sum(d => d.OdCount)
            }).Take(5).OrderByDescending(d=>d.Total).ToListAsync();
   
            var data = salesData.Select(o =>
            {

                var pro = allProduct.FirstOrDefault(d => d.Pid == o.pid);

                return new
                {
                    name = pro?.Pname,
                    value = o.Total,
                };
            }).ToList();

            return Result(1, data:data);
        }
        /// <summary>
        /// 实物类销量
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetSwSales()
        {




            //查询订单表里的产品id
            var iq = await _order_IOC._order_Detail_EFCore.QueryAll(d => d.OdIsPay == 1).Select(d => d.OdPId).ToListAsync();
            //查询所有的服务类产品
            var allProduct = await _product_IOC._sys_product_EFCore.QueryAll(d => d.Ptype == 2).ToListAsync();
            //是否包含服务类的产品
            var od = await _product_IOC._sys_product_EFCore.QueryAll(d => iq.Contains(d.Pid) && d.Ptype == 2).Select(d => d.Pid).ToListAsync();

            var salesData = await _order_IOC._order_Detail_EFCore.QueryAll(d => d.OdIsPay == 1 && od.Contains(d.OdPId!)).GroupBy(d => d.OdPId).Select(d => new
            {
                pid = d.Key,
                Total = d.Sum(d => d.OdCount)
            }).Take(5).OrderByDescending(d => d.Total).ToListAsync();

            var data = salesData.Select(o =>
            {

                var pro = allProduct.FirstOrDefault(d => d.Pid == o.pid);

                return new
                {
                    name = pro?.Pname,
                    value = o.Total,
                };
            }).ToList();

            return Result(1, data: data);




        }
        /// <summary>
        /// 每月销量数据
        /// </summary>
        /// <returns></returns>

        public async Task<Api_Response_Dto> MonthsSales()
        {



            var monthlySales = await _order_IOC._order_Detail_EFCore.QueryAll(d => d.OdIsPay == 1).ToListAsync();


          var iq=  monthlySales.GroupBy(d => new
            {
                d.OdCreateTime!.Value.Date.Year,
                d.OdCreateTime.Value.Date.Month,
            }).Select(g=>new
            {
                year=g.Key.Year,
                Month=g.Key.Month,
                total=g.Sum(d => d.OdCount)
            }).OrderBy(d=>d.year).ThenBy(d=>d.Month).ToList();


            var result = Enumerable.Range(1, 12)
         .Select(month => new
         {
             Month = month+"月",
             Total = iq
                 .Where(ms => ms.Month == month)
                 .Sum(ms => ms.total)
         })
         .ToList();

            return Result(1,data: result);
        }

      

    }
}
